package com.roc.web.action.agent;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007YJPosAgentFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.YjPosAgent;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 *批量分配终端 
 * @author zhaofeng
 *
 */
@Component
@Scope("prototype")
@Namespace("/serialNumLeading")
public class SerialNumLeadingAction extends BaseAction{
	private Logger logger = LogManager.getLogger(SerialNumLeadingAction.class);

	private List<Operators> operatorsList = new ArrayList<Operators>();
	private String msg;
	private File upload;
	private YjPosInfo posInfo;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();

	private Operators merchant;
    private String code;

	@Autowired
	IorgService orgService;
	@Autowired
	IAgentInfoService agentInfoService;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	ITerminalService terminalService;
	@Autowired 
	IMerchantServices merchantServices;
	
	@Action(value = "serialNumLeadingJsp", results = { @Result(name = "success", location = "/pages/agent/serialNum_leading.jsp") })
	public String serialNumLeadingJspAction() throws Exception {
		String value = null;
		 Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		org();
		Operators operators = new Operators();
		operators = powerInfoService.loadOperatorsById(new Long(code));
	    value  = SexStatus.valueOfCode(operators.getSex()).getName();
		operators.setSex(value);
		value  = Role.valueOfCode(operators.getRoleType()).getName();
		operators.setRoleType(value);
		value  = OperatorsStatus.valueOfCode(operators.getStatus()).getName();
		operators.setStatus(value);
		/*
		//查询所属代理商
        if(logingMerchant.getRoleType().equals(Role.AGENT.getCode())){
        	operatorsList=merchantServices.listOperatorsAgent(logingMerchant.getOrgCode());
        }else{
        	operatorsList=merchantServices.listOperatorsAgent(null);
        }*/

		for(OrgBean bean:orgList){
			if(operators.getOrgCode().equals(bean.getOrg_code())){
				operators.setOrgName(bean.getOrg_name());
			}
		}

		// 取代理商父类id
		Long supId = operators.getSuperiorId();
		// 取上级代理商信息
		Operators supOperator = powerInfoService.loadOperatorsById( supId );
		
		operators.setSuperiorName(supOperator.getRealName());
		/*
		for (Operators opera : operatorsList) {
			if(opera.getId() == operators.getSuperiorId()){
				operators.setSuperiorName(opera.getRealName());
			}
		}*/
		/*
		Map<String,String> brandMap=ConfigProperties.getPOSBrand();
	    Map<String,String> nameMap=ConfigProperties.getPOSName();
		Map<String,String> typeMap=ConfigProperties.getPOSType();

		getSession().setAttribute("brandMap", brandMap);
		getSession().setAttribute("nameMap", nameMap);
		getSession().setAttribute("typeMap", typeMap);*/
		getRequest().setAttribute("agent", operators);
		getRequest().setAttribute("code", code);
		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		return SUCCESS;
	}
	
	
	@Action(value = "serialNumLeadingLeading", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = { 
			@Result(location = "/message.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")
	    })
	public String serialNumLeadingAction() throws Exception{
       
		
		try {
			org();
			Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		    StringBuffer errorMsg = new StringBuffer();
			if(upload == null){
				msg="请选择文件";
				return SUCCESS;
			}
			// 厂商
			String posBrand = posInfo.getPosBrand();
	//		posBrand = "00";
			if(null == posBrand || "".equals(posBrand) || "-1".equals(posBrand)){
				msg="请选择厂商";
				return SUCCESS;
			}
			String msg = "";//错误显示信息
			int index = 0;//
			FileProcessor processor = new Excel2007YJPosAgentFileProcessor();
			List<YjPosAgent> list = (List<YjPosAgent>) processor.process(upload);
			String context = "";//提示信息
			Operators operator = powerInfoService.loadOperatorsById(new Long(code));//分批终端序列号目的对象

			if(list==null || list.size()==0){
				errorMsg.append("你好，你的Execl文件中不存在数据记录!");
				addActionError(errorMsg.toString());
			}
			else{
				List<YjPosAgent> existAgentList = new ArrayList<YjPosAgent>();
				List<YjPosAgent> noExistPosInfoList = new ArrayList<YjPosAgent>();
				
				List<YjPosAgent> deleteRepeatAgentList = getDeleteRepeatAgent(list);
				
				Map<String, List<YjPosAgent>> map = new HashMap<String, List<YjPosAgent>>();
				
				if(deleteRepeatAgentList!=null && deleteRepeatAgentList.size()>0){
					if(deleteRepeatAgentList.size()>1000){
						errorMsg.append("你好，你的Execl文件中在数据记录数超过1000条,请分批导入！");
						addActionError(errorMsg.toString());
					}else{
						map = terminalService.getSeriaNumListForExeclMap(deleteRepeatAgentList, logingMerchant, posInfo, operator);
						if(map.get("posInfo")!=null && map.get("posInfo").size()>0){
							noExistPosInfoList = map.get("posInfo");
							errorMsg.append("选择的Execl文件中部分终端序列号在系统中不存在，请确认！！！ 系统不存在的终端序列号如下:");
							for(YjPosAgent posinfo:noExistPosInfoList){
								errorMsg.append(posinfo.getSerialNum()).append(",").append("\n");
							}
							index = errorMsg.toString().lastIndexOf(",");
							msg = errorMsg.toString().substring(0, index);
							addActionError(msg);
						}
						if(map.get("posAgent")!=null){
							existAgentList = map.get("posAgent");
	    					context = "操作员【" + logingMerchant.getAccountNo() + "】成功分配【"+ (deleteRepeatAgentList.size()-existAgentList.size())+ "】个终端序列号给代理商"+"【"+operator.getAccountNo()+"】";
	    					errorMsg.append(context);
							//errorMsg.append(",选择的Execl文件中如下终端SN号已分配给了【"+operator.getAccountNo()+"】");
							//existAgentList = terminalService.SerialNumTerByForExecl(deleteRepeatAgentList, logingMerchant, posInfo, code);//保存数据
							if(existAgentList.size()>0){//存在重复数据
								errorMsg.append("以下序列号已经分配或SN无效:");
								for(YjPosAgent agent:existAgentList){
									errorMsg.append(agent.getSerialNum()).append(",").append("\n");
								}
								index = errorMsg.toString().lastIndexOf(",");
								msg = errorMsg.toString().substring(0, index);
								addActionError(msg);
							}
							else{//全部导入成功
		    					context = "操作员【" + logingMerchant.getAccountNo() + "】成功分配【"+ deleteRepeatAgentList.size()+ "】个终端序列号给用户"+"【"+operator.getAccountNo()+"】";
								addActionError(context);
							}
						}
					}	
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
    /**
     * 去除重复终端序列号数据
     * @param list
     * @return
     */
	private List<YjPosAgent> getDeleteRepeatAgent(List<YjPosAgent> list){
		List<YjPosAgent>  newList = new ArrayList<YjPosAgent>();
		Map<String,YjPosAgent> map = new HashMap<String,YjPosAgent>();
		for(YjPosAgent agent:list){
			if(agent.getSerialNum()!=null && !"".equals(agent.getSerialNum())){
				if(map.get(agent.getSerialNum())==null){
				  map.put(agent.getSerialNum(), agent);
				}
			}	
		}
		for(String key : map.keySet()) {
			newList.add(map.get(key));
		}
		return newList;
	}
	// 查询机构
	public void org() throws Exception {
		Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		orgList = orgService.listOrgs(logingOperators);
	}

	public List<Operators> getOperatorsList() {
		return operatorsList;
	}

	public void setOperatorsList(List<Operators> operatorsList) {
		this.operatorsList = operatorsList;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public YjPosInfo getPosInfo() {
		return posInfo;
	}

	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
}
